﻿<%@ WebHandler Language="C#" Class="AuthHandler" %>

using System;
using System.Web;
using System.Collections;
using System.Data;
using StarTech.DBUtility;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Net.NetworkInformation;


public class AuthHandler : IHttpHandler
{
    AdoHelper ado = AdoHelper.CreateHelper(StarTech.Util.AppConfig.DBInstance);
    string memberId = "";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        if (context.Request.Cookies["memberInfo"] != null && Common.CheckUser(context.Request.Cookies["memberInfo"].Value))
        {
            memberId = context.Request.Cookies["memberInfo"].Value.Split(new string[] { "$$" }, StringSplitOptions.RemoveEmptyEntries)[0];
            string flag = Common.NullToEmpty(context.Request["flag"]);
            string authStep = isAuth();
            bool isFront = false;
            if (flag.Equals("isauth"))
            {
                context.Response.Write(authStep);
            }
            else if (flag.Equals("info"))
            {
                context.Response.Write(getInfo());
            }
            else if (authStep.Equals("1"))
            {
                context.Response.Write("您好，您的账户已经认证，无需再次认证");
            }
            else
            {
                switch (flag)
                {
                    case "addinfo":
                        string trueName = Common.NullToEmpty(context.Request["trueName"]);
                        string idCard = Common.NullToEmpty(context.Request["idCard"]);
                        context.Response.Write(addInfo(trueName, idCard));  //代表上传成功
                        break;
                    case "upload":
                        if (context.Request.Files.Count == 0)
                        {
                            context.Response.Write("请上传文件");  //代表文件为空
                        }
                        else
                        {
                            try
                            {
                                isFront = Convert.ToBoolean(context.Request["isfront"]);
                            }
                            catch
                            {
                                isFront = false;
                            }
                            string info = uploadPic(context.Request.Files[0], isFront);
                            context.Response.Write(info);  //代表上传成功
                        }
                        break;
                    case "delpic":
                        try
                        {
                            isFront = Convert.ToBoolean(context.Request["isfront"]);
                        }
                        catch
                        {
                            isFront = false;
                        }
                        context.Response.Write(DeletePic(isFront));
                        break;
                    default:
                        context.Response.Write("0");
                        break;
                }
            }
        }
        else
        {
            context.Response.Write("请重新登录");
        }
    }

    private string getInfo()
    {
        string strSql = @"select top 1 TrueName,PersonIDCode,PersonIDCodePhoto,applyPic,applyPic2 from T_Member_Info a
                    left join T_Member_Pic b on a.MemberId=b.memberId where a.memberid=@memberid and applyType='auth'";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@memberid",memberId),
        };
        return JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p).Tables[0]);
    }

    private string uploadPic(HttpPostedFile uploadFile, bool isFront)
    {
        addPicRecord();
        string fileTail = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf('.')).ToLower();
        string savePath = "/upload/seller/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MMdd") + "/";
        if (!Directory.Exists(HttpContext.Current.Server.MapPath(savePath)))
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(savePath));
        savePath += DateTime.Now.ToString("HHmmssffff") + fileTail;
        uploadFile.SaveAs(HttpContext.Current.Server.MapPath(savePath));

        string strSql = "update t_member_pic set " + (isFront ? "applyPic" : "applyPic2") + "=@path where ifpass='0' and memberid=@memberid and applyType='auth';";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@memberid",memberId),
            new SqlParameter("@path",savePath),
        };
        ado.ExecuteSqlNonQuery(strSql, p);
        return "1_$$_" + savePath;
    }

    private string addInfo(string trueName, string idCard)
    {
        addPicRecord();
        string birthDay = getBirthDayFromID(idCard);
        try { DateTime t = DateTime.Parse(birthDay); if (t.Year > 2100 || t.Year < 1901) { birthDay = DateTime.Now.ToString("yyyy-MM-dd"); } }
        catch { return "请输入正确的身份证号"; }
        string sex = getGenderFromID(idCard);
        if (sex.Length > 5)
            return sex;
        string strSql = "update T_Member_Info set TrueName=@TrueName,PersonIDCode=@PersonIDCode,BirthDay=@BirthDay,Sex=@Sex where MemberId=@MemberId;";
        SqlParameter[] p = new SqlParameter[]
        {
            new SqlParameter("@TrueName",trueName),
            new SqlParameter("@PersonIDCode",idCard),
            new SqlParameter("@BirthDay",birthDay),
            new SqlParameter("@Sex",sex),
            new SqlParameter("@MemberId",memberId),
        };
        string result=ado.ExecuteSqlNonQuery(strSql, p).ToString();
        return result;
    }

    private string DeletePic(bool isFront)
    {
        string picWord = "applyPic" + (isFront ? "" : "2");
        string strSql1 = "select " + picWord + " from t_member_pic where MemberId=@MemberId and applyType='auth';";
        SqlParameter[] p1 = new SqlParameter[]
        {
            new SqlParameter("@MemberId",memberId),
        };
        string picpath = ado.ExecuteSqlScalar(strSql1, p1).ToString();
        File.Delete(HttpContext.Current.Server.MapPath(picpath));

        string strSql2 = "update t_member_pic set " + picWord + "='' where MemberId=@MemberId and applyType='auth';";
        SqlParameter[] p2 = new SqlParameter[]
        {
            new SqlParameter("@MemberId",memberId),
        };
        return ado.ExecuteSqlNonQuery(strSql2, p2).ToString();
    }

    private string isAuth()
    {
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@memberid",memberId)
        };
        DataTable dt = ado.ExecuteSqlDataset("select ifpass,nopassinfo from t_member_pic where memberid=@memberid and applyType='auth'", p).Tables[0];
        if (dt.Rows.Count == 0)
        {
            return "-1"; //尚未提交认证信息
        }
        else
        {
            if (Common.NullToZero(dt.Rows[0]["ifpass"]) == 1)
                return "1"; //已认证
            else
            {
                string noPassInfo = Common.NullToEmpty(dt.Rows[0]["nopassinfo"]);
                if (string.IsNullOrEmpty(noPassInfo))
                    return "0"; //正在认证
                else
                    return noPassInfo;
            }
        }
    }

    private void addPicRecord()
    {
        string strSql = "select * from t_member_pic where memberid=@memberId and applyType='auth'";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@memberid",memberId)
        };
        DataTable dt = ado.ExecuteSqlDataset(strSql, p).Tables[0];
        if (dt.Rows.Count == 0)
        {
            string strSql2 = "insert into t_member_pic(applyId,memberId,applyTime,ifPass,applyType) values(@applyId,@memberId,@applyTime,@ifPass,@applyType)";
            SqlParameter[] p2 = new SqlParameter[] {
                new SqlParameter("@applyId",IdCreator.CreateId("T_Member_Pic", "applyId")),
                new SqlParameter("@memberId",memberId),
                new SqlParameter("@applyTime",DateTime.Now),
                new SqlParameter("@ifPass",'0'),
                new SqlParameter("@applyType","auth"),
            };
            ado.ExecuteSqlNonQuery(strSql2, p2);
        }
    }

    private string getBirthDayFromID(string idCard)
    {
        try
        {
            if (idCard.Length == 15)
            {
                return Convert.ToDateTime("19" + idCard.Substring(6, 2) + "-" + idCard.Substring(8, 2) + "-" + idCard.Substring(10, 2)).ToString("yyyy-MM-dd");
            }
            else if (idCard.Length == 18)
            {
                return Convert.ToDateTime(idCard.Substring(6, 4) + "-" + idCard.Substring(10, 2) + "-" + idCard.Substring(12, 2)).ToString("yyyy-MM-dd");
            }
            else
            {
                return DateTime.Now.ToString();
            }
        }
        catch (Exception)
        {
            return DateTime.Now.ToString();
        }
    }

    private string getGenderFromID(string idCard)
    {
        try
        {
            if (idCard.Length == 15)
            {
                return Convert.ToInt32(idCard.Substring(14, 1)) % 2 == 1 ? "男" : "女";
            }
            else if (idCard.Length == 18)
            {
                return Convert.ToInt32(idCard.Substring(16, 1)) % 2 == 1 ? "男" : "女";
            }
            else
            {
                return "";
            }
        }
        catch (Exception)
        {
            return "请输入正确的身份证号";
        }

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}